package message

import (
	"encoding/json"
	"github.com/garyburd/redigo/redis"
	"log"
	"rhelper"
	"time"
	"userws"
)

type Message struct {
	Type     string `json:"type"`
	Id       int    `json:"id"`
	To       string `json:"to"`
	From     string `json:"from"`
	Title    string `json:"title"`
	Abstract string `json:"abstract"`
	Detail   string `json:"detail"`
	Stime    int    `json:"stime"`
}

func SendMessage(msg Message) error {
	rconn := rhelper.Pool().Get()
	defer rconn.Close()

	to := msg.To

	id, err := redis.Int(rconn.Do("INCR", rhelper.MsgIdHolder))
	if err != nil {
		log.Println("SendMessage err:", err)
		return err
	}

	msg.Id = id

	msg.Stime = int(time.Now().Unix())

	b, err := json.Marshal(msg)
	if err != nil {
		log.Println("SendMessage error:", err)
		return err
	}

	rconn.Send("MULTI")
	rconn.Send("HSET", rhelper.MsgHash+to, id, b)
	rconn.Send("RPUSH", rhelper.MsgURHash+to, id)
	_, err = rconn.Do("EXEC")
	if err != nil {
		log.Println("SendMessage err:", err)
		return err
	}

	// notify user if he is online
	userws.Send2WS(to, b)
	return nil
}

func LoadUnReadMessage(whose string, start int, stop int) ([]string, error) {
	rconn := rhelper.Pool().Get()
	defer rconn.Close()

	ids, err := redis.Strings(rconn.Do("LRANGE", rhelper.MsgURHash+whose, start, stop))
	if err != nil {
		log.Println("LoadUnReadMessage err:", err)
		return nil, err
	}

	rconn.Send("MULTI")
	for _, id := range ids {
		rconn.Send("HGET", rhelper.MsgHash+whose, id)
	}
	msgs, err := redis.Strings(rconn.Do("EXEC"))

	if err != nil {
		log.Println("LoadUnReadMessage err:", err)
		return nil, err
	}

	return msgs, nil
}

func SetMessageRead(whose string, ids []string) {
	rconn := rhelper.Pool().Get()
	defer rconn.Close()

	rconn.Send("MULTI")
	for _, id := range ids {
		rconn.Send("LREM", rhelper.MsgURHash+whose, 1, id)
	}
	_, err := rconn.Do("EXEC")
	if err != nil {
		log.Println("SetMessageRead err:", err)
		return
	}
}
